package com.xu.cloud.common.tx;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Objects;

/**
 * jdbc事务管理
 *
 * @author xuguan
 * @since 2025/2/11
 * @see java.sql.Connection
 */
public class JdbcTransaction implements ITransaction {

    private final DataSource dataSource;
    private Connection connection;

    public JdbcTransaction(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public void startTransaction() {
        openConnection();
    }

    @Override
    public void commit() {
        if (Objects.isNull(connection)) {
            throw new UnsupportedOperationException("transaction not start");
        }

        try {
            connection.commit();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void rollback() {
        if (Objects.isNull(connection)) {
            throw new UnsupportedOperationException("transaction not start");
        }

        try {
            connection.rollback();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void endTransaction() {
        try {
            if (Objects.nonNull(connection)) {
                // 恢复自动提交
                connection.setAutoCommit(true);
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    protected void openConnection() {
        try {
            connection = dataSource.getConnection();
            // 开启事务
            connection.setAutoCommit(false);
            connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
